package com.cuhk.gulimall.product.app;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.cuhk.gulimall.product.entity.CategoryEntity;
import com.cuhk.gulimall.product.service.CategoryService;
import com.cuhk.common.utils.R;



/**
 * 商品三级分类
 *
 * @author chenyuijing
 * @email torchsam@aliyun.com
 * @date 2024-06-10 12:02:33
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查出所有分类、子分类
     * 以树形结构组装
     */
    @GetMapping("/list/tree")
    public R list(){
        // PageUtils page = categoryService.queryPage(params);
        List<CategoryEntity> menu = categoryService.listWithTree();
        return R.ok().put("menu", menu);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId){
		CategoryEntity category = categoryService.getById(catId);
        return R.ok().put("data", category);
    }

    /**
     * 保存
     */
    // @RequestMapping("/save")
    @PostMapping("/save")
    public R save(@RequestBody CategoryEntity category){
		categoryService.save(category);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody CategoryEntity category){
		// categoryService.updateById(category);
        categoryService.updateCascade(category);
        return R.ok();
    }

    /**
     * 删除
     * 读取JSON参数
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
		// categoryService.removeByIds(Arrays.asList(catIds));
        categoryService.removeMenusByIds(catIds);
        return R.ok();
    }

    /**
     * 在拖拽功能中
     * 更新拖拽后，受影响元素的排序
     * @param categories
     * @return
     */
    @PostMapping("/update/sort")
    public R updateSort(@RequestBody CategoryEntity[] categories){
        categoryService.updateBatchById(Arrays.asList(categories));
        return R.ok();
    }

}
